'use strict';

const Service = require('egg').Service;

class FriendService extends Service {
    //1.关键词查找用户
    async search(keyword){
        // if(keyword){
            let search=[];
            let nameResult=await this.app.model.User.findAll( { where: { name: { $like: `%${keyword}%` } } } );//用户名模糊查找
            let mailResult=await this.app.model.User.findAll( { where: { email: { $like: `%${keyword}%` } } } );//邮箱模糊查找
            // let groupResult=await this.app.model.Group.findAll( { where: { name: { $like: `%${keyword}%` } } } );
            search.push(...nameResult);
            search.push(...mailResult);
            let searchResult =await this.unique(search,"id");//数组去重
            // searchResult.push(...groupResult);
            if(searchResult){
                return searchResult
            }else{
                return{
                    message:'未搜索到相关用户!'
                }
            } 
        // }   
    }
    
    //对象数组去重
    async unique(arr, key) {
        if (!arr) return arr
        if (key === undefined) return [...new Set(arr)]
        const map = {
            'string': e => e[key],
            'function': e => key(e),
        }
        const fn = map[typeof key]
        const obj = arr.reduce((o,e) => (o[fn(e)]=e, o), {})
        return Object.values(obj)
    }

    //2.判断是不是好友和判断好友状态
    async friendState(user_id,friend_id){
        let judgeResult = await this.app.model.Friend.findOne({where:{user_id:user_id,friend_id:friend_id}});
        if(judgeResult){
            if(judgeResult.state==0){
                return{
                    state:0,
                    message:'好友'
                }
            }else if(judgeResult.state==1){
                return{
                    state:1,
                    message:'已申请'
                }

            }else if(judgeResult.state==2){
                return{
                    state:2,
                    message:'同意'
                }
            }
        }else{
            return{
                state:3,
                message:'加好友'
            }
        }
   }

   //3. 好友信息详情(并判断好友状态)
   async friendDetail(user_id,friend_id){
    let friendDetail=await this.ctx.service.user.userDetail(friend_id);   
    let detailData=await this.app.model.Friend.findOne({where:{user_id:user_id,friend_id:friend_id}});
    // if(detailData){ 
        let friendState=await this.friendState(user_id,friend_id)
        return {
            detailData,
            friendDetail,
            friendState
        }
    //   }else{
    //       return{
    //           friendDetail,
    //           code:400,
    //           message:'非好友关系！'
    //       }
    //   }
    }

   //4.好友昵称修改
   async changeFriendName(user_id,friend_id,name){
       await this.app.model.Friend.update({
           name:name
       },{
           where:{
               user_id:user_id,
               friend_id:friend_id
           }
       })
       return true
   }

   //5. 好友申请方（添加好友表）
   async friendBuild1(user_id,friend_id,state,nickName){
       try{
           let friendData={
           user_id:user_id,
           friend_id:friend_id,
           name:nickName,
           state:state,
           time:new Date(),
           lasttime:new Date()
       };
       await this.app.model.Friend.create(friendData);
       return true;
       }catch(error){
           return false
       }
      
   }
   //被申请方
   async friendBuild2(user_id,friend_id,state){
    try{
        let friendData={
        user_id:user_id,
        friend_id:friend_id,
        state:state,
        time:new Date(),
        lasttime:new Date()
    };
    await this.app.model.Friend.create(friendData);
    return true;
    }catch(error){
        return false
    }
   
}
   
   //6. 好友申请（申请词添加到一对一消息表）
   async insertMsg(user_id,friend_id,msg,type){
       try{
          let data ={
                user_id:user_id,
                friend_id:friend_id,
                message:msg,          //消息内容
                types:type,           //消息类型
                time:new Date(),        //发送时间
                state:1               //消息状态
            };
            await this.app.model.Message.create(data);
            return true; 
       }catch(error){
           return false;
       }
       
   }

   //7. 更新好友最后通讯时间
   async upFriendLastTime(user_id,friend_id){
       try{
          await this.app.model.Friend.update({
           lasttime:new Date()
        },{   //此处$or未测试
            where:{$or:[{user_id:user_id,friend_id:friend_id},{user_id:friend_id,friend_id:user_id}]
            }
        }); 
        return true
       }catch(error){
           return false
       }
       
   }

   //8. 好友申请
   async applyFriend(user_id,friend_id,msg,nickName){
       try{
            //判断是否申请过
        let searchResult=await this.app.model.Friend.findOne(
            {where:{
                user_id:user_id,
                friend_id:friend_id
            }});
        if(searchResult){//已经申请过了，就更新一下时间
            await this.upFriendLastTime(user_id,friend_id);
            await this.insertMsg(user_id,friend_id,msg,0)
        }else{ //初次申请就创建好友表
            await this.friendBuild1(user_id,friend_id,2,nickName);
            await this.friendBuild2(friend_id,user_id,1);
            await this.insertMsg(user_id,friend_id,msg,0)
        } return true
       }catch(error){
           return false
       }
       
    }

    //9. 同意好友申请(更新好友状态state)
    async updateFriendState(user_id,friend_id,nickName){
        try{
            await this.app.model.Friend.update({
            state:0
            },{ 
                where:{$or:[{user_id:user_id,friend_id:friend_id},{user_id:friend_id,friend_id:user_id}]}
            });
            await this.app.model.Friend.update({name:nickName},{where:{user_id:user_id,friend_id:friend_id}})
            return true
        }catch(error){
            return false
        }
        
    }

    //10. 拒绝/删除好友
    async deleteFriend(user_id,friend_id){
        try{
           await this.app.model.Friend.destroy({   //此处$or未测试
            where:{$or:[{user_id:user_id,friend_id:friend_id},{user_id:friend_id,friend_id:user_id}]
            }
            }); 
            return true
        }catch(error){
            return false
        }
        
    }
   //检索所有好友及其详情
    // async getFriendList(id){
    //    let friendlist= await this.app.model.Friend.findAll({
    //         where:{user_id:id}
    //     })
    //     //将检索到的对象中的friend_id组成数组返回
    //     let friendIdList=[];
    //     for(let i of friendlist){
    //         friendIdList.push(i.friend_id)
    //     }
        
    //     //检索全部好友信息
    //     let friendLists=[];
    //     for(let i of friendIdList){
    //     let friendMessage= await this.app.model.User.findOne({
    //         where:{id:i}
    //         })
    //         friendLists.push(friendMessage)
    //     }
    //     return {friendIdList,friendLists}      
    // }
    async getFriendList(id) {
      const friendList=await this.app.model.Friend.findAndCountAll({
        'order':[['time','DESC']],
        attributes:["lasttime","state","time"], 
        include:[{attributes:["id","name","imgurl"],model:this.app.model.User,as:'user'}],
        where:{user_id:id}
      });
      return friendList;
      }
}


module.exports = FriendService;